package com.efast.cafe.util;

import javax.crypto.KeyGenerator;  
import javax.crypto.Mac;  
import javax.crypto.SecretKey;  
import javax.crypto.spec.SecretKeySpec;


import com.google.common.base.Strings;

import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class HMAC {

	/** 
     * 定义加密方式 
     * MAC算法可选以下多种算法 
     * <pre> 
     * HmacMD5 
     * HmacSHA1 
     * HmacSHA256 
     * HmacSHA384 
     * HmacSHA512 
     * </pre> 
     */  
    private final static String KEY_MAC = "HmacSHA256";  
  
    /** 
     * 全局数组 
     */  
    private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",  
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };  
  
    /** 
     * 构造函数 
     */  
    public HMAC() {  
  
    }  
  
    /** 
     * BASE64 加密 
     * @param key 需要加密的字节数组 
     * @return 字符串 
     * @throws Exception 
     */  
    public static String encryptBase64(byte[] key) throws Exception {  
    	return Base64.getEncoder().encodeToString(key);
    }  
  
    /** 
     * BASE64 解密 
     * @param key 需要解密的字符串 
     * @return 字节数组 
     * @throws Exception 
     */  
    public static byte[] decryptBase64(String key) throws Exception {  
        return Base64.getDecoder().decode(key);  
    }  
  
    /** 
     * 初始化HMAC密钥 
     * @return 
     */  
    public static String init() {  
        SecretKey key;  
        String str = "";  
        try {  
            KeyGenerator generator = KeyGenerator.getInstance(KEY_MAC);  
            key = generator.generateKey();  
            str = encryptBase64(key.getEncoded());  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return str;  
    }  
  
    /** 
     * HMAC加密 
     * @param data 需要加密的字节数组 
     * @param key 密钥 
     * @return 字节数组 
     */  
    public static byte[] encryptHMAC(byte[] data, String key) {  
        SecretKey secretKey;  
        byte[] bytes = null;  
        try {  
            secretKey = new SecretKeySpec(key.getBytes(), KEY_MAC);  
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());  
            mac.init(secretKey);  
            bytes = mac.doFinal(data);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return bytes;  
    }  
  
    /** 
     * HMAC加密 
     * @param data 需要加密的字符串 
     * @param key 密钥 
     * @return 字符串 
     */  
    public static String encryptHMAC(String data, String key) {  
        if (Strings.isNullOrEmpty(data)) {  
            return null;  
        }  
        byte[] bytes = encryptHMAC(data.getBytes(), key);  
        return byteArrayToHexString(bytes);  
    }  
  
  
    /** 
     * 将一个字节转化成十六进制形式的字符串 
     * @param b 字节数组 
     * @return 字符串 
     */  
    private static String byteToHexString(byte b) {  
        int ret = b;  
        //System.out.println("ret = " + ret);  
        if (ret < 0) {  
            ret += 256;  
        }  
        int m = ret / 16;  
        int n = ret % 16;  
        return hexDigits[m] + hexDigits[n];  
    }  
  
    /** 
     * 转换字节数组为十六进制字符串 
     * @param bytes 字节数组 
     * @return 十六进制字符串 
     */  
    private static String byteArrayToHexString(byte[] bytes) {  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < bytes.length; i++) {  
            sb.append(byteToHexString(bytes[i]));  
        }  
        return sb.toString();  
    }  
  
    /** 
     * 测试方法 
     * @param args 
     */  
    public static void main(String[] args) throws Exception {  
    	
    	String co = "{\"name\":\"xuanming.feng\"}";
    	System.out.println(HMAC.encryptBase64(co.getBytes()));
    	System.out.println(HMAC.encryptHMAC(HMAC.encryptBase64(co.getBytes()), "ewiuwieo298432jdwiejiweiw"));
    	
    	String content = "<GetDealerMasterDataResponse><Dealer_Master_Data><DealerCode>D0001</DealerCode><DealerName_EN>EN NAME</DealerName_EN><DealerName_CN>中文名</DealerName_CN><DealerShortName_EN>aaa</DealerShortName_EN><DealerShortName_CN>啊啊啊</DealerShortName_CN><Country>CN</Country><Province>DD</Province><City>SH</City><Street>01</Street><PostCode>A1</PostCode><EmailAddress>1222@22.COM</EmailAddress><Fax>12332</Fax><ContactPerson>03</ContactPerson><Telephone>13000000000</Telephone><RegionCode>R001</RegionCode><RegionName>区域1</RegionName><Status>01</Status></Dealer_Master_Data><Dealer_Master_Data><DealerCode>D0002</DealerCode><DealerName_EN>EN NAME2</DealerName_EN><DealerName_CN>中文名2</DealerName_CN><DealerShortName_EN>aaa2</DealerShortName_EN><DealerShortName_CN>啊啊啊2</DealerShortName_CN><Country>CN</Country><Province>DD</Province><City>SH</City><Street>01</Street><PostCode>A1</PostCode><EmailAddress>1222@22.COM</EmailAddress><Fax>123321111</Fax><ContactPerson>03</ContactPerson><Telephone>13000000000</Telephone><RegionCode>R002</RegionCode><RegionName>区域2</RegionName><Status>03</Status></Dealer_Master_Data></GetDealerMasterDataResponse>";
    	
    	
    	System.out.println(HMAC.encryptHMAC(HMAC.encryptBase64(content.getBytes()), "ewiuwieo298432jdwiejiweiw"));
    	
    	System.out.println(HMAC.init());
//    	String s1 = "9f6e44b830fdab6a2a3f034be281286bc7f8e344720147fb16a3d4f5f9157ccf";
//    	String s2 = "9f6e44b830fdab6a2a3f034be281286bc7f8e344720147fb16a3d4f5f9157ccf";
//    	String s3 = "9f6e44b830fdab6a2a3f034be281286bc7f8e344720147fb16a3d4f5f9157ccf";
//    	String s4 = "9f6e44b830fdab6a2a3f034be281286bc7f8e344720147fb16a3d4f5f9157ccf";
//    	String s5 = "9f6e44b830fdab6a2a3f034be281286bc7f8e344720147fb16a3d4f5f9157ccf";
////    	System.out.println(HMAC.init());
    	String miyao = "aEUjjsauUjK93";
//    	String text = "hello";
//    	String jiamihou = encryptHMAC(text, miyao);
////    //	String jiamihou2 = byteArrayToHexString(encryptHMAC(text.getBytes(), HMAC.init(miyao)));
//    	 System.out.println(jiamihou);  
    	 
    //	 System.out.println(jiamihou2);  
    	
//        String key = HMAC.init();  
//        key = "4B5gRYlQBF8cTRHxpktZCtD0CAD594AzEgY0SG3ygh4=";
//        System.out.println("Mac密钥:\n" + key);  
//        String word = "efast";  //24fda726774e50f38d53dd68b1837243391d3ac839db91aacbb200748f3deb09
//        							//24fda726774e50f38d53dd68b1837243391d3ac839db91aacbb200748f3deb09
//        System.out.println(encryptHMAC(word, key));  
//    	String miyao = "aEUjjsauUjK93";
//    	System.out.println("eyJtb25pdG9yVGltZSI6IjIwMTctNi0xNiIsInF5YnlqeHh6IjowLjg1LCJxeWJ5anN4eiI6MS4zNSwieWpjc2JsIjowLjI1fQ==".length());
//        String message = "{\"messageId\":\"NDczMzNjNThjNjJjNGQ5ZmI2ZTgyYWEwMWIwZTE1ZjgyMDE3MDYxNjE2MTMwMTM2OQ==\",\"busObject\":\"eyJtb25pdG9yVGltZSI6IjIwMTctNi0xNiIsInF5YnlqeHh6IjowLjg1LCJxeWJ5anN4eiI6MS4zNSwieWpjc2JsIjowLjI1fQ==\"}";
//       System.out.println(HMAC.encryptHMAC(message, miyao));
//       System.out.println("base64------------------------");
//       System.out.println(new sun.misc.BASE64Encoder().encode("{\"monitorTime\":\"2017-6-16\",\"qybyjxxz\":0.85,\"qybyjsxz\":1.35,\"yjcsbl\":0.25}".getBytes()));
//       System.out.println(HMAC.encryptBase64("{\"monitorTime\":\"2017-6-16\",\"qybyjxxz\":0.85,\"qybyjsxz\":1.35,\"yjcsbl\":0.25}".getBytes()));
//        
//        String dataStr = "{\"message\":{\"messageId\":\"NDczMzNjNThjNjJjNGQ5ZmI2ZTgyYWEwMWIwZTE1ZjgyMDE3MDYxNjE2MTMwMTM2OQ==\",\"busObject\":\"eyJtb25pdG9yVGltZSI6IjIwMTctNi0xNiIsInF5YnlqeHh6IjowLjg1LCJxeWJ5anN4eiI6MS4zNSwieWpjc2JsIjowLjI1fQ==\"},\"hmac\":\"94af2dac094880b9ebf2412fab4efbb12052bc7a931eef15046d86e1ac133a89\",\"time\":\"yyyy-MM-dd HH:mm\",\"version\":\"1\"}";
      
        //原始数据
//        String s = "{\"message\":{\"messageId\":\"5aab0c9c520148ab8452761331bd86c720170705124747425\",\"busObject\":{\"monitorTime\": \"2017-05-25 15:15:22\",\"al\": \"1:2;2:1;3:2;4:0;5:0;6:0;7:0;8:0;\",\"mb\": \"0\",\"yz\": \"1\",\"ygyl\": \"1\",\"clzznd\": \"1\",\"pv\": \"0\",\"clzzqd\": \"0\",\"clzztz\": \"0\",\"xyhqg\": \"0\"}},\"hmac\": \"\",\"time\": \"2017-6-13 15:15\",\"version\": \"1\"}";
//       //原始message
//        String yuanshiMessage = "{\"messageId\":\"5aab0c9c520148ab8452761331bd86c720170705124747425\",\"busObject\":{\"monitorTime\": \"2017-05-25 15:15:22\",\"al\": \"1:2;2:1;3:2;4:0;5:0;6:0;7:0;8:0;\",\"mb\": \"0\",\"yz\": \"1\",\"ygyl\": \"1\",\"clzznd\": \"1\",\"pv\": \"0\",\"clzzqd\": \"0\",\"clzztz\": \"0\",\"xyhqg\": \"0\"}}";
//        System.out.println(yuanshiMessage);
//        String codeMessageId = HMAC.encryptBase64("5aab0c9c520148ab8452761331bd86c720170705124747425".getBytes());
//        String codeMessageObj = HMAC.encryptBase64("{\"monitorTime\": \"2017-05-25 15:15:22\",\"al\": \"1:2;2:1;3:2;4:0;5:0;6:0;7:0;8:0;\",\"mb\": \"0\",\"yz\": \"1\",\"ygyl\": \"1\",\"clzznd\": \"1\",\"pv\": \"0\",\"clzzqd\": \"0\",\"clzztz\": \"0\",\"xyhqg\": \"0\"}".getBytes());
//        System.out.println("编码后的MessageId:");
//        System.out.println(codeMessageId);
//        System.out.println("编码后的busObject:");
//        System.out.println(codeMessageObj);
//        
//        //编码后的message
//        String codeMessage = "{\"messageId\":\"NWFhYjBjOWM1MjAxNDhhYjg0NTI3NjEzMzFiZDg2YzcyMDE3MDcwNTEyNDc0NzQyNA==\",\"busObject\":\"eyJtb25pdG9yVGltZSI6ICIyMDE3LTA1LTI1IDE1OjE1OjIyIiwiYWwiOiAiMToyOzI6MTszOjI7NDowOzU6MDs2OjA7NzowOzg6MDsiLCJtYiI6ICIwIiwieXoiOiAiMSIsInlneWwiOiAiMSIsImNsenpuZCI6ICIxIiwicHYiOiAiMCIsImNsenpxZCI6ICIwIiwiY2x6enR6IjogIjAiLCJ4eWhxZyI6ICIwIn0==\"}";
//        System.out.println("编码后的message:");
//        System.out.println(codeMessage);
//        
//        String hmac = HMAC.encryptHMAC(codeMessage, miyao);
//        System.out.println("hmac令牌：");
//        System.out.println(hmac);
//        
//        //最终上传到服务器的数据
//        String dataStr = "{\"message\":{\"messageId\":\"NWFhYjBjOWM1MjAxNDhhYjg0NTI3NjEzMzFiZDg2YzcyMDE3MDcwNTEyNDc0NzQyNA==\",\"busObject\":\"eyJtb25pdG9yVGltZSI6ICIyMDE3LTA1LTI1IDE1OjE1OjIyIiwiYWwiOiAiMToyOzI6MTszOjI7NDowOzU6MDs2OjA7NzowOzg6MDsiLCJtYiI6ICIwIiwieXoiOiAiMSIsInlneWwiOiAiMSIsImNsenpuZCI6ICIxIiwicHYiOiAiMCIsImNsenpxZCI6ICIwIiwiY2x6enR6IjogIjAiLCJ4eWhxZyI6ICIwIn0==\"},\"hmac\": \""+hmac+"\",\"time\": \"2017-6-13 15:15\",\"version\": \"1\"}";
//        System.out.println("最终上传到服务器的数据：");
//        System.out.println(dataStr);
//        SocketCallbackData callbackData = null;
//		
//		SocketIOInData socketIOInData = null;
//		SocketIOInMessage socketInMessage = null;
//		try{
//			JSONObject dataJson = new JSONObject().fromObject(dataStr);
//			System.out.println(dataJson.toString());
//			socketIOInData = (SocketIOInData)JSONObject.toBean(dataJson,SocketIOInData.class);
//			socketInMessage = socketIOInData.getMessage();
//		}catch(Exception e){
//			System.out.println("解析json数据错误");
//			System.out.println(SocketCallbackData.ERROR_DATA_ERROR);
//		}
//		
//		if(null!=socketIOInData && socketInMessage!=null){
//			//校验sec
//			if(StringUtils.isBlank(socketInMessage.getMessageId())){
//				System.out.println(SocketCallbackData.ERROR_DATA_ERROR);
//				return;
//			}else{//校验hmac动态令牌是否正确
//					JSONObject messageJson = new JSONObject();
//					messageJson.put("messageId", socketInMessage.getMessageId());
//					messageJson.put("busObject", socketInMessage.getBusObject());
//					
//					System.out.println(messageJson.toString());
//					String validCode = HMAC.encryptHMAC(messageJson.toString(), miyao);
//					if(!validCode.equals(socketIOInData.getHmac())){
//						System.out.println(SocketCallbackData.ERROR_HMAC_ERROR);
//						return;
//					}
//					
//					
//					try{
//						socketInMessage.setMessageId(new String(HMAC.decryptBase64(socketInMessage.getMessageId())));
//						if(socketInMessage.getBusObject()!=null){
//							System.out.println(new String(HMAC.decryptBase64(socketInMessage.getBusObject().toString())));
//							socketInMessage.setBusObject(new String(HMAC.decryptBase64(socketInMessage.getBusObject().toString())));
//							
//						}
//						
//						System.out.println(socketInMessage.getMessageId());
//						System.out.println(socketInMessage.getBusObject().toString());
//					}catch(Exception e){
//						System.out.println(SocketCallbackData.ERROR_DECODE_ERROR);
//						return;
//					}
//        
//			}
//    }  
    }
}
